package cn.lysj.framework.common.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.lysj.framework.base.BaseController;
import cn.lysj.framework.common.CommonConstant;
import cn.lysj.framework.common.annotation.CurrentUser;
import cn.lysj.framework.common.domain.Permission;
import cn.lysj.framework.common.domain.User;
import cn.lysj.framework.common.security.permission.MySecurityMetadataSource;
import cn.lysj.framework.common.service.PermissionService;
import cn.lysj.framework.common.service.RolePermissionService;
import cn.lysj.framework.common.utils.web.ParamUtil;
import cn.lysj.framework.common.utils.web.Resp;
import cn.lysj.framework.common.validate.Message;
import cn.lysj.framework.common.validate.annotation.Validator;
import cn.lysj.framework.common.validate.entity.Medusa;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zk
 * @description 权限表控制层
 * @create 2018-07-25 15:32:54
 **/
@Slf4j
@RestController
@Api(description = "权限表管理接口")
@RequestMapping("/admin/permission")
public class PermissionController extends BaseController<Permission>{

    @Resource
    private PermissionService permissionService;

    @Override
    public PermissionService getService() {
        return permissionService;
    }

    @Resource
    private MySecurityMetadataSource mySecurityMetadataSource;

    @Resource
    private RolePermissionService rolePermissionService;

    @GetMapping("/findMenuList")
    public Resp findMenuList(@CurrentUser User user){
        //该用户的所有权限 已排序去重
        List<Permission> list = permissionService.findByUserId(user.getId());

        List<Permission> menuList = new ArrayList<>();

        //筛选一级页面
        for(Permission p : list){
            if(CommonConstant.PERMISSION_PAGE.equals(p.getType())&&CommonConstant.LEVEL_ONE.equals(p.getLevel())){
                menuList.add(p);
            }
        }

        //筛选二级页面
        List<Permission> secondMenuList = new ArrayList<>();
        for(Permission p : list){
            if(CommonConstant.PERMISSION_PAGE.equals(p.getType())&&CommonConstant.LEVEL_TWO.equals(p.getLevel())){
                secondMenuList.add(p);
            }
        }

        //筛选二级页面拥有的按钮权限
        List<Permission> buttonPermissions = new ArrayList<>();
        for(Permission p : list){
            if(CommonConstant.PERMISSION_OPERATION.equals(p.getType())&&CommonConstant.LEVEL_THREE.equals(p.getLevel())){
                buttonPermissions.add(p);
            }
        }

        //匹配二级页面拥有权限
        for(Permission p : secondMenuList){
            List<Permission> buttonMenu = new ArrayList<>();
            for(Permission pe : buttonPermissions){
                if(p.getId().equals(pe.getParentId())){
                    buttonMenu.add(pe);
                }
            }
            p.setChildren(buttonMenu);
        }

        //匹配一级页面拥有二级页面
        for(Permission p : menuList){
            List<Permission> secondMenu = new ArrayList<>();
            for(Permission pe : secondMenuList){
                if(p.getId().equals(pe.getParentId())){
                    secondMenu.add(pe);
                }
            }
            p.setChildren(secondMenu);
        }
        return new Resp(menuList);
    }

    /**
     * @author zk
     * @date 2018-08-13 22:04
     * @Description 获取权限菜单树
     */
    @GetMapping("/find_all_list")
    @ApiOperation(value = "获取权限菜单树")
    public Resp findAllList(){
        List<Permission> permissions = permissionService.findByLevelOrderBySortOrderDesc(CommonConstant.LEVEL_ONE);
        for (Permission p1 : permissions) {
            List<Permission> children1 = permissionService.findByParentIdOrderBySortOrder(p1.getId());
            p1.setChildren(children1);
            for(Permission p2 : children1){
                List<Permission> children2 = permissionService.findByParentIdOrderBySortOrder(p2.getId());
                p2.setChildren(children2);
            }
        }
        return new Resp(permissions);
    }

    @Override
    @PostMapping("/save")
    @ApiOperation(value = "添加权限")
    public Resp save(@Validator Permission entity) {
        permissionService.update(entity);
        //重新加载权限表
        mySecurityMetadataSource.loadResourceDefine();
        return new Resp("添加成功");
    }

    @Override
    @PostMapping("/update")
    @ApiOperation(value = "修改权限")
    public Resp update(Permission entity) {
        if(ParamUtil.isBlank(entity.getId())){
            return new Resp(Resp.PARAM_ERROR,"参数错误，请重试");
        }
        Permission permission = getService().findOne(entity.getId());
        if(permission == null){
            return new Resp(Resp.PARAM_ERROR,"查无此数据，请刷新重试");
        }
        //获取Hutool拷贝实例
        CopyOptions copyOptions = CopyOptions.create();
        //忽略为null值得属性
        copyOptions.setIgnoreNullValue(true);
        //进行属性拷贝
        BeanUtil.copyProperties(entity,permission,copyOptions);
        //对实体类中的@validation注解进行校验
        Medusa medusa = Message.getMsg(permission);
        if(!medusa.isFlag()){
            return new Resp(Resp.PARAM_ERROR, medusa.getMessage());
        }
        permissionService.update(permission);
        //重新加载权限表
        mySecurityMetadataSource.loadResourceDefine();
        return new Resp("修改成功");
    }

    @Override
    @PostMapping("/delete")
    @ApiOperation(value = "删除权限")
    public Resp delete(String[] ids) {
        for (String id : ids) {
            Permission permission = permissionService.findOne(id);
            if(permission == null){
                return new Resp("参数错误,请重试");
            }
            rolePermissionService.deleteByPermissionId(id);
            permissionService.delete(id);
        }
        mySecurityMetadataSource.loadResourceDefine();
        return new Resp("删除成功");
    }
}
